package com.qkbb.admin.kuibu.qkbb.imageloader;

import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;

/**
 * @author DigHammer
 * */
public class LruMemoryCache {

	private static final String TAG = "LruMemoryCache";
    /**向内存申请8M的空间，这里可以自己定义，也可以
     * 通过获取系统分配给应用的最大内存然后取其1/4*/
	private int mCacheSize = 8 * 1024 * 1024;
	/** Android 系统提供的LRUCache类 */
	private LruCache<String, Bitmap> mMemoryCache = new LruCache<String, Bitmap>(
			mCacheSize) {
		// 必须重写此方法，来测量Bitmap的大小
		@Override
		protected int sizeOf(String key, Bitmap value) {
			return value.getRowBytes() * value.getHeight();
		}

		@Override
		protected void entryRemoved(boolean evicted, String key,
				Bitmap oldValue, Bitmap newValue) {
			// 当对象移除的时候，将其添加到软引用中
			softMemoryCache.put(key, new SoftReference<Bitmap>(oldValue));
		}

	};

	private static final int SOFT_CACHE_CAPACITY = 16;

	private static LinkedHashMap<String, SoftReference<Bitmap>> softMemoryCache = new LinkedHashMap<String, SoftReference<Bitmap>>(
			SOFT_CACHE_CAPACITY, 0.75f, true);

	private static LruMemoryCache instance = null;

	public synchronized static LruMemoryCache getInstance() {
		if (instance == null) {
			instance = new LruMemoryCache();
		}
		return instance;
	}

	/**
	 * 添加Bitmap到内存缓存
	 * 
	 */
	public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
		if (getBitmapFromMemCache(key) == null && bitmap != null) {
			synchronized (mMemoryCache) {
				mMemoryCache.put(key, bitmap);
			}
		}
	}

	/**
	 * 从内存缓存中获取一个Bitmap
	 * 
	 */
	public Bitmap getBitmapFromMemCache(String key) {
		synchronized (mMemoryCache) {
			Bitmap bitmap = mMemoryCache.get(key);
			if (bitmap != null) {
				return bitmap;
			}
			// 硬引用缓存区间中读取失败，从软引用缓存区间读取
			synchronized (softMemoryCache) {
				SoftReference<Bitmap> bitmapReference = softMemoryCache
						.get(key);
				if (bitmapReference != null) {
					Bitmap softBitmap = bitmapReference.get();
					if (softBitmap != null) {
						return softBitmap;
					}
				} else {
					//对象为空时，从哈希表中移除该键值对。
					softMemoryCache.remove(key);
				}
			}
		}
		return null;
	}

}
